package com.zsl.swing.redis.desktop.window.list;

import com.zsl.swing.redis.desktop.utils.CollectionUtils;

import javax.swing.*;
import java.util.*;

public class ZslListModel<T> extends AbstractListModel<T>{

    private Vector<T> list;

    private Comparator<T> comparator;

    public ZslListModel(){
        this.list = new Vector<>();
    }

    public ZslListModel(Comparator<T> comparator){
        this.comparator = comparator;
        this.list = new Vector<>();
    }

    public synchronized Vector<T> getList() {
        if(!Objects.isNull(comparator)){
            this.list.sort(comparator);
        }

        return list;
    }


    public List<T> copyCurrentList(){
        Vector<T> current = this.getList();
        return new ArrayList<>(current);
    }

    public synchronized void setList(Vector<T> list) {
        this.list = list;
    }

    @Override
    public synchronized int getSize() {
        return this.list.size();
    }

    @Override
    public synchronized T getElementAt(int index) {
        return this.list.get(index);
    }

    public synchronized void addOneElement(T element){
        this.list.add(element);
        this.fireIntervalAdded(this, 0, 0);
    }

    public synchronized void addElementList(List<T> elementList){
        if(!CollectionUtils.isEmpty( elementList)){
            this.list.addAll(elementList);

            this.fireIntervalAdded(this, 0, this.list.size());
        }
    }

    public synchronized void removeOneElement(T element){
        int index = this.list.indexOf(element);

        if(index != -1){
            this.list.remove(index);
            this.fireIntervalRemoved(this, index, index);
        }

    }

    public synchronized void removeAllElementList(){
        int size = this.list.size();

        if(size > 0){
            this.list.clear();
            this.fireIntervalRemoved(this, 0, size);
        }

    }

}
